//
//  EnergyDispatch.m
//  cocoapodText
//
//  Created by apple on 16/10/19.
//  Copyright © 2016年 apple. All rights reserved.
//


#import "ShiPei.h"
#import "EnergyDispatch.h"
#import <Foundation/Foundation.h>
@interface EnergyDispatch ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)NSMutableArray *queryDataInfos;
@end

@implementation EnergyDispatch

- (void)viewDidLoad {
    _pageRecord=15;
    _pageAllNum=1;
    [super viewDidLoad];
    [self.view setBackgroundColor:FUIColorFromRGB(0xf4f4f4)];
    [self GetMainContentView];
    _planIden=@"";
    [_planIdenEdit setText:@""];
}


/**
 * 边界
 * top:(0, 0, kScreenW, 10)
 * bottom:(0, kScreenH-10, kScreenW,10)
 * left:(0, 0, 10, kScreenH)
 * right:(kScreenW-170, 0, 10, kScreenH)
 */
-(void)GetMainContentView{
    //内容栏
    _dispatchAllBackView=[[UIView alloc]initWithFrame:CGRectMake([ShiPei CGFloatMakeScale:15], [ShiPei CGFloatMakeScale:15], [ShiPei CGFloatMakeScale:TabChildContentW],  kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:FSCommonBottomH])];
    [self.view addSubview:_dispatchAllBackView];
    [_dispatchAllBackView setBackgroundColor:[UIColor clearColor]];
    [_dispatchAllBackView setUserInteractionEnabled:YES];
    ///菜单栏
    [self initMenuView];
    ///表格栏
    [self initTableView];
}

-(void)initMenuView{
    UIView *MessageMenuView=[[UIView alloc]initWithFrame:[ShiPei CGRectMakeScale:0 :0 :TabChildContentW :40]];
    [_dispatchAllBackView addSubview:MessageMenuView];
    [MessageMenuView setUserInteractionEnabled:YES];
    [MessageMenuView setBackgroundColor:[UIColor whiteColor]];
    
    UIImageView *ModuleImage=[[UIImageView alloc]initWithFrame:[ShiPei CGRectMakeScale:15 :15 :15 :15]];
    [MessageMenuView addSubview:ModuleImage];
    [ModuleImage setImage:[UIImage imageNamed:@"fs_main_id_image.png"]];
    
    UILabel *ModuleLabel=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:40 :10 :120 :20]];
    [MessageMenuView addSubview:ModuleLabel];
    [ModuleLabel setText:@"能源调度"];
    [ModuleLabel setTextColor:FUIColorFromRGB(0x333333)];
    [ModuleLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:28]]];
    
    UILabel *energyTypeLabel=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:430 :0 :100 :40]];
    [MessageMenuView addSubview:energyTypeLabel];
    [energyTypeLabel setTextAlignment:NSTextAlignmentCenter];
    [energyTypeLabel setUserInteractionEnabled:YES];
    [energyTypeLabel setText:@"方案标识"];
    [energyTypeLabel setTextColor:FUIColorFromRGB(0x333333)];
    [energyTypeLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:25]]];
    
    
    UIView *planIdenEditBGView=[[UIView alloc]initWithFrame:[ShiPei CGRectMakeScale:530 :7.5 :200 :25]];
    [MessageMenuView addSubview:planIdenEditBGView];
    [planIdenEditBGView setUserInteractionEnabled:YES];
    [planIdenEditBGView setBackgroundColor:[UIColor clearColor]];
    [planIdenEditBGView.layer setBorderWidth:1];
    [planIdenEditBGView.layer setBorderColor:[FUIColorFromRGB(0xdfe2e6) CGColor]];
    [planIdenEditBGView.layer setCornerRadius:10];
    [planIdenEditBGView.layer setMasksToBounds:YES];
    
    _planIdenEdit=[[UITextField alloc]initWithFrame:[ShiPei CGRectMakeScale:10 :0.5 :180 :24]];
    [planIdenEditBGView addSubview:_planIdenEdit];
    _planIdenEdit.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
    _planIdenEdit.placeholder=@"";
    _planIdenEdit.backgroundColor=[UIColor whiteColor]; //背景色
    _planIdenEdit.font=[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:24]]; //设置字体名字和字体大小;
    _planIdenEdit.returnKeyType = UIReturnKeyDefault;//return键的类型
    _planIdenEdit.keyboardType = UIKeyboardTypeDefault;//键盘类型
    _planIdenEdit.textAlignment = NSTextAlignmentLeft; //文本显示的位置默认为居左
    _planIdenEdit.textColor = FUIColorFromRGB(0x333333);
    _planIdenEdit.text = @"";//设置显示的文本内容//设置委托
    
    //在弹出的键盘上面加一个view来放置退出键盘的Done按钮
    UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    [topView setBarStyle:UIBarStyleDefault];
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];
    NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace, doneButton, nil];
    [topView setItems:buttonsArray];
    [_planIdenEdit setInputAccessoryView:topView];
    
    UIButton *queryButton=[[UIButton alloc]initWithFrame:[ShiPei CGRectMakeScale:760 :15/2 :50 :25]];
    [MessageMenuView addSubview:queryButton];
    [queryButton setBackgroundImage:[CommonTool createImageWithColor:FUIColorFromRGB(0x3388cb) Frame:[ShiPei CGRectMakeScale:0 :0 :50 :25]] forState:UIControlStateNormal];
    [queryButton setBackgroundImage:[CommonTool createImageWithColor:FUIColorFromRGB(0x639ed7)  Frame:[ShiPei CGRectMakeScale:0 :0 :50 :25]] forState:UIControlStateHighlighted];
    [queryButton.layer setMasksToBounds:YES];
    [queryButton.layer setCornerRadius:5];
    [queryButton setTitle:@"查询" forState:UIControlStateNormal];
    [queryButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [queryButton.titleLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:26]]];
    [queryButton addTarget:self action:@selector(onClickQuery) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)initTableView{
    
    UIScrollView *dispatchAllView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, [ShiPei CGFloatMakeScale:55], [ShiPei CGFloatMakeScale:TabChildContentW], kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:80]-[ShiPei CGFloatMakeScale:FSCommonBottomH])];
    [_dispatchAllBackView addSubview:dispatchAllView];
    [dispatchAllView setUserInteractionEnabled:YES];
    [dispatchAllView setBackgroundColor:[UIColor whiteColor]];
    [dispatchAllView setContentSize:CGSizeMake([ShiPei CGFloatMakeScale:TabChildContentW-30], kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:80])];
    
    DispatchTopView *dispatchTopView=[[DispatchTopView alloc]initWithFrame:[ShiPei CGRectMakeScale:15 :20 :TabChildContentW-30 :35]];
    [dispatchAllView addSubview:dispatchTopView];
    [dispatchTopView setBackgroundColor:FUIColorFromRGB(0x639ed7)];
    [dispatchTopView setUserInteractionEnabled:YES];
    //名称Name
    //类型Type
    //方案标识Load
    //累计调度小时数Number
    //承诺降负荷Price
    //实际降负荷StartTime
    //完成率EndTime
    //内容Content
    [dispatchTopView setName:@"能耗对象"];
    [dispatchTopView setType:@"能耗类型"];
    [dispatchTopView setLoad:@"方案标识"];
    [dispatchTopView setNumber:@"累计调度小时数"];
    [dispatchTopView setPrice:@"预估降量"];
    [dispatchTopView setStartTime:@"实际降量"];
    [dispatchTopView setEndTime:@"完成率"];
    [dispatchTopView setContent:@"状态"];
    
    _dispatchInfoTable=[[UITableView alloc]initWithFrame:CGRectMake([ShiPei CGFloatMakeScale:15], [ShiPei CGFloatMakeScale:55], [ShiPei CGFloatMakeScale:TabChildContentW-30], kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:150])];
    [dispatchAllView addSubview:_dispatchInfoTable];
    [_dispatchInfoTable setBackgroundColor:[UIColor clearColor]];
    [_dispatchInfoTable setUserInteractionEnabled:YES];
    [_dispatchInfoTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_dispatchInfoTable setDelegate:self];
    [_dispatchInfoTable setDataSource:self];
    
    // Set the callback（Once you enter the refresh status，then call the action of target，that is call [self loadMoreData]）
    _dispatchInfoTable.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

-(void)loadMoreData{
    if (_pageNum+1>_pageAllNum) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 拿到当前的上拉刷新控件，结束刷新状态
            [_dispatchInfoTable.mj_footer endRefreshing];
        });
    }else{
        APIEnergyDispatchManager *manager=[APIEnergyDispatchManager alloc];
        manager.delegate=self;
        [manager fsgy_api_energy_dispatch_withFalg:EDLoadMore planIden:_planIden pageNum:[NSString stringWithFormat:@"%d",_pageNum+1] pageRecord:[NSString stringWithFormat:@"%d",_pageRecord]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [_dispatchInfoTable reloadData];
            // 拿到当前的上拉刷新控件，结束刷新状态
            [_dispatchInfoTable.mj_footer endRefreshing];
        });
    }
    
}

-(void)fristInitialLoad{
    APIEnergyDispatchManager *manager=[APIEnergyDispatchManager alloc];
    manager.delegate=self;
    [manager fsgy_api_energy_dispatch_withFalg:EDInit planIden:_planIden pageNum:[NSString stringWithFormat:@"%d",_pageNum] pageRecord:[NSString stringWithFormat:@"%d",_pageRecord]];
}

-(void)onEnergyDispatchManager:(APIEnergyDispatchManager *)manager result:(NSDictionary *)result Flag:(NSString *)flag{
    if ([flag isEqualToString:EDLoadMore]) {
        //解析数据
        NSArray *list=[result objectForKey:@"list"];
        if ([list count]>0) {
            _pageNum++;
            NSMutableArray *models=[NSMutableArray array];
            for (int j=0; j<[_queryDataInfos count]; j++) {
                [models addObject:[_queryDataInfos objectAtIndex:j]];
            }
            _queryDataInfos =[NSMutableArray array];
            //颜色问题
            if ([_queryDataInfos count]%2==0) {
                for (int i=0; i<[list count]; i++) {
                    NSDictionary *dispatchDic=[list objectAtIndex:i];
                    NSString *orgName=[CommonTool getStringFromNSDictionary:dispatchDic key:@"orgName" defaultValue:@""];
                    NSString *esCodeName=[CommonTool getStringFromNSDictionary:dispatchDic key:@"esCodeName" defaultValue:@""];
                    NSString *idenkey=[CommonTool getStringFromNSDictionary:dispatchDic key:@"idenkey" defaultValue:@""];
                    NSString *LJHOUR=[CommonTool getStringFromNSDictionary:dispatchDic key:@"LJHOUR" defaultValue:@""];
                    NSString *ygjnl=[CommonTool getStringFromNSDictionary:dispatchDic key:@"ygjnl" defaultValue:@""];
                    NSString *sjjnl=[CommonTool getStringFromNSDictionary:dispatchDic key:@"sjjnl" defaultValue:@""];
                    NSString *completeRate=[CommonTool getStringFromNSDictionary:dispatchDic key:@"completeRate" defaultValue:@""];
                    NSString *isuedName=[CommonTool getStringFromNSDictionary:dispatchDic key:@"isuedName" defaultValue:@""];
                    dispatchInfo *model;
                    if (i%2==0) {
                        model=[dispatchInfo dispatchInfoWithName:orgName type:esCodeName load:idenkey number:LJHOUR price:ygjnl startTime:sjjnl endTime:completeRate content:isuedName color:@"1"];
                        [models addObject:model];
                    }else{
                        model=[dispatchInfo dispatchInfoWithName:orgName type:esCodeName load:idenkey number:LJHOUR price:ygjnl startTime:sjjnl endTime:completeRate content:isuedName color:@"0"];
                        [models addObject:model];
                    }
                }
            }else{
                for (int i=0; i<[list count]; i++) {
                    NSDictionary *dispatchDic=[list objectAtIndex:i];
                    NSString *orgName=[CommonTool getStringFromNSDictionary:dispatchDic key:@"orgName" defaultValue:@""];
                    NSString *esCodeName=[CommonTool getStringFromNSDictionary:dispatchDic key:@"esCodeName" defaultValue:@""];
                    NSString *idenkey=[CommonTool getStringFromNSDictionary:dispatchDic key:@"idenkey" defaultValue:@""];
                    NSString *LJHOUR=[CommonTool getStringFromNSDictionary:dispatchDic key:@"LJHOUR" defaultValue:@""];
                    NSString *ygjnl=[CommonTool getStringFromNSDictionary:dispatchDic key:@"ygjnl" defaultValue:@""];
                    NSString *sjjnl=[CommonTool getStringFromNSDictionary:dispatchDic key:@"sjjnl" defaultValue:@""];
                    NSString *completeRate=[CommonTool getStringFromNSDictionary:dispatchDic key:@"completeRate" defaultValue:@""];
                    NSString *isuedName=[CommonTool getStringFromNSDictionary:dispatchDic key:@"isuedName" defaultValue:@""];
                    dispatchInfo *model;
                    if (i%2==0) {
                        model=[dispatchInfo dispatchInfoWithName:orgName type:esCodeName load:idenkey number:LJHOUR price:ygjnl startTime:sjjnl endTime:completeRate content:isuedName color:@"0"];
                        [models addObject:model];
                    }else{
                        model=[dispatchInfo dispatchInfoWithName:orgName type:esCodeName load:idenkey number:LJHOUR price:ygjnl startTime:sjjnl endTime:completeRate content:isuedName color:@"1"];
                        [models addObject:model];
                    }
                    
                }
            }
            _queryDataInfos=[models copy];
        }
        
    }else if ([flag isEqualToString:EDInit]) {
        _pageNum=1;
        _recordCount=[[CommonTool getStringFromNSDictionary:result key:@"list.page.recordCount" defaultValue:@"0"] intValue];
        _pageAllNum=_recordCount/15;
        int yushu=_recordCount%15;
        if (yushu!=0) {
            _pageAllNum=_pageAllNum+1;
        }
        //解析数据
        NSArray *list=[result objectForKey:@"list"];
        _queryDataInfos =[NSMutableArray array];
        NSMutableArray *models=[NSMutableArray array];
        
        for (int i=0; i<[list count]; i++) {
            NSDictionary *dispatchDic=[list objectAtIndex:i];
            NSString *orgName=[CommonTool getStringFromNSDictionary:dispatchDic key:@"orgName" defaultValue:@""];
            NSString *esCodeName=[CommonTool getStringFromNSDictionary:dispatchDic key:@"esCodeName" defaultValue:@""];
            NSString *idenkey=[CommonTool getStringFromNSDictionary:dispatchDic key:@"idenkey" defaultValue:@""];
            NSString *LJHOUR=[CommonTool getStringFromNSDictionary:dispatchDic key:@"LJHOUR" defaultValue:@""];
            LJHOUR=[CommonTool addXiaoShuDian:LJHOUR];
            NSString *ygjnl=[CommonTool getStringFromNSDictionary:dispatchDic key:@"ygjnl" defaultValue:@""];
            ygjnl=[CommonTool addXiaoShuDian:ygjnl];
            NSString *sjjnl=[CommonTool getStringFromNSDictionary:dispatchDic key:@"sjjnl" defaultValue:@""];
            sjjnl=[CommonTool addXiaoShuDian:sjjnl];
            NSString *completeRate=[CommonTool getStringFromNSDictionary:dispatchDic key:@"completeRate" defaultValue:@""];
            NSString *isuedName=[CommonTool getStringFromNSDictionary:dispatchDic key:@"isuedName" defaultValue:@""];
            dispatchInfo *model;
            if (i%2==0) {
                model=[dispatchInfo dispatchInfoWithName:orgName type:esCodeName load:idenkey number:LJHOUR price:ygjnl startTime:sjjnl endTime:completeRate content:isuedName color:@"1"];
                [models addObject:model];
            }else{
                model=[dispatchInfo dispatchInfoWithName:orgName type:esCodeName load:idenkey number:LJHOUR price:ygjnl startTime:sjjnl endTime:completeRate content:isuedName color:@"0"];
                [models addObject:model];
            }
        }
        _queryDataInfos=[models copy];
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            // 处理耗时操作的代码块...
            //通知主线程刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新
                [_dispatchInfoTable reloadData];
            });
        });
    }
}


-(void)onClickQuery{
    _planIden=_planIdenEdit.text;
    APIEnergyDispatchManager *manager=[APIEnergyDispatchManager alloc];
    manager.delegate=self;
    [manager fsgy_api_energy_dispatch_withFalg:EDInit planIden:_planIden pageNum:[NSString stringWithFormat:@"%d",_pageNum] pageRecord:[NSString stringWithFormat:@"%d",_pageRecord]];
}

#pragma mark - 数据源方法
#pragma mark 返回分组数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//设置rowHeight
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [ShiPei CGFloatMakeScale:35];
}

#pragma mark 返回每组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.queryDataInfos.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark返回每行的单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //1.到缓存中去取cell
    static NSString *ID=@"ID";
    //2.没有则创建cell
    DispatchTableCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    if (cell==nil) {
        cell=[[DispatchTableCell
               alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    //3.设置cell的数据
    cell.dispatchinfo=self.queryDataInfos[indexPath.row];
    //4.返回cell
    return cell;
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _pageNum=1;
    [self fristInitialLoad];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

//关闭键盘
-(void) dismissKeyBoard{
    [_planIdenEdit resignFirstResponder];
}
@end
